#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#define ARGS_CHECK(argc, num)                     {                                                 if (argc != num)                              {                                                 fprintf(stderr, args error!n);             return -1;                                }                                         }
#define ERROR_CHECK(ret, num, msg)  {                                           if (ret == num)                     {                                       perror(msg);                        exit(1);                        }                           }   
void my_msgsnd(pid_t pid,int fd);
void my_msgrcv(int fd);
void sigfun(){
    wait(NULL);
    exit(1);
}
int main(int argc, char *argv[]){  
    int fd_s = socket(PF_INET,SOCK_STREAM,0);
    ERROR_CHECK(fd_s,-1,"socket");
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(atoi(argv[2]));
    saddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(fd_s,(void *)&saddr,sizeof saddr);
    ERROR_CHECK(-1,ret,"connect");
    puts("connect success!");
    pid_t pid =fork();
    if (pid == 0)
    {
       my_msgrcv(fd_s);
    }else if(pid > 0){
        signal(SIGCHLD,sigfun);
        my_msgsnd(pid,fd_s);
        
    }else{
        perror("fork");
        return -1;
    }
    
    
    return 0;  
}
void my_msgsnd(pid_t pid,int fd){
    char buf[128];
    int ret ;
    while (1)
    {
        fgets(buf,sizeof(buf),stdin);
        ret = write(fd,buf,sizeof(buf));
        if (ret <= 0)
        {
            kill(pid,SIGUSR1);
            exit(0);
        }
        if(0 == strcasecmp(buf,"quit")){
            kill(pid,SIGUSR1);
            exit(0);
        }
    }
    
}
void my_msgrcv(int fd){
    char buf[128];
    int ret;
    while (1)
    {
         ret =read(fd,buf,sizeof(buf));
         ERROR_CHECK(-1,ret,"read");
        if (0 == ret)
        {
            exit(0);
        }
        if(0 == strcasecmp(buf,"quit\n")){
           
            exit(0);
        }
        printf(">>%s",buf);
    }
    

}